package dhm.com.hpx.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Animatable;
import android.net.Uri;
import android.os.AsyncTask;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.controller.ControllerListener;
import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.drawee.view.SimpleDraweeView;
import com.facebook.imagepipeline.image.ImageInfo;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import dhm.com.hpx.R;
import dhm.com.hpx.base.BaseActivity;
import dhm.com.hpx.base.Presenter.PressenterImpl;
import dhm.com.hpx.base.netWork.Constant;
import dhm.com.hpx.base.netWork.LoginContract;
import dhm.com.hpx.entity.Bean;
import dhm.com.hpx.entity.GetPosterBean;
import dhm.com.hpx.entity.GetUserInfoBean;
import dhm.com.hpx.utils.SpUtils;
import dhm.com.hpx.utils.WXUtil;
import dhm.com.hpx.utils.mapapi.Util;

public class PosterActivity extends BaseActivity implements LoginContract.IView {

    @BindView(R.id.poster_image)
    SimpleDraweeView posterImage;
    @BindView(R.id.image)
    SimpleDraweeView image;
    @BindView(R.id.nick)
    TextView nick;
    @BindView(R.id.job)
    TextView job;
    @BindView(R.id.erweima)
    SimpleDraweeView erweima;
    private PressenterImpl pressenter;
    private String poster_id;
    private String uid;

    private IWXAPI api;
    private GetPosterBean getPosterBean;

    @Override
    protected int getLayout() {
        return R.layout.activity_poster;
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        api = WXAPIFactory.createWXAPI(this, Constant.Wx_APP_ID,false);
        pressenter = new PressenterImpl();
        pressenter.attachView(this);

        poster_id = getIntent().getStringExtra("poster_id");

        uid = SpUtils.getString(this, "uid");

        Map<String,String> map=new HashMap<>();
        map.put("token", Constant.TOKEN);
        map.put("poster_id",poster_id);
        map.put("uid",uid);

        pressenter.sendMessage(this,Constant.poster_info,map, GetPosterBean.class);



    }

    @Override
    protected void initData() {

    }

    @Override
    public void requesta(Object data) {
        if (data instanceof GetPosterBean){
            getPosterBean = (GetPosterBean) data;
            if (getPosterBean.getCode()==1){
                //获取图片真正的宽高
                Glide.with(this).asBitmap().load(Constant.PATH+ getPosterBean.getData().getVideo_info().getPoster_url()).into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(Bitmap bitmap, Transition<? super Bitmap> transition) {
                        int width = bitmap.getWidth();
                        int height = bitmap.getHeight();
                        imageShow(posterImage,Constant.PATH+ getPosterBean.getData().getVideo_info().getPoster_url(),height,width);
                    }
                });
                erweima.setImageURI(getPosterBean.getData().getUser_info().getCardurl());

            }

            Map<String,String> map=new HashMap<>();
            map.put("token",Constant.TOKEN);
            map.put("uid",uid);
            pressenter.sendMessage(this,Constant.get_userinfo,map, GetUserInfoBean.class);


        }else if (data instanceof GetUserInfoBean){
            GetUserInfoBean getUserInfoBean= (GetUserInfoBean) data;
            if (getUserInfoBean.getCode()==1){
                image.setImageURI(Constant.PATH+getUserInfoBean.getData().getHeadsmall());
                job.setText("专注"+getUserInfoBean.getData().getBusiness()+"，欢迎前来咨询。");
                nick.setText(getUserInfoBean.getData().getUser_nickname());
            }


        }

    }

    /**
     * 设置宽高的图片
     * @param image
     * @param imageURI
     * @param tempHeight
     */
    private void imageShow(final SimpleDraweeView image, String imageURI,final int tempHeight,final int tempWidth) {
        DraweeController controller = Fresco.newDraweeControllerBuilder()
                .setOldController(image.getController())
                .setControllerListener(new ControllerListener<ImageInfo>() {
                    @Override
                    public void onSubmit(String id, Object callerContext) {

                    }

                    @Override
                    public void onFinalImageSet(String id, ImageInfo imageInfo, Animatable animatable) {
                        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) image.getLayoutParams();
                        params.height = tempHeight;
                        params.width = tempWidth;
                        image.setLayoutParams(params);
                    }

                    @Override
                    public void onIntermediateImageSet(String id, ImageInfo imageInfo) {

                    }

                    @Override
                    public void onIntermediateImageFailed(String id, Throwable throwable) {

                    }

                    @Override
                    public void onFailure(String id, Throwable throwable) {

                    }

                    @Override
                    public void onRelease(String id) {

                    }
                })
                .setUri(Uri.parse(imageURI))
                .build();
        image.setController(controller);
    }




    @Override
    public void fail(String error) {

    }

    @OnClick({R.id.back, R.id.extension})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.extension:
                //初始化一个WXWebpageObject，填写url
                if (getPosterBean==null){
                    Toast.makeText(this, "正在加载，请稍后...", Toast.LENGTH_SHORT).show();
                    return;
                }
                WXWebpageObject webpage = new WXWebpageObject();
//                webpage.webpageUrl ="http://www.quqike.cn/appapi/appletscode/getwxacode/uid/"+uid+"/type/2/article_id/"+poster_id;

                webpage.webpageUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+Constant.urlappid+"&redirect_uri=" +
                        Constant.PATH+"appapi/extension/shouquan/uid/" + uid + "/type/3/target_id/"+poster_id +
                        "&response_type=code&scope=snsapi_userinfo&state=1&connect_redirect=1#wechat_redirect";

//用 WXWebpageObject 对象初始化一个 WXMediaMessage 对象
                WXMediaMessage msg = new WXMediaMessage(webpage);
                msg.title =getPosterBean.getData().getVideo_info().getPoster_title();
                msg.description =getPosterBean.getData().getVideo_info().getPoster_desc();

                if (getPosterBean.getData().getVideo_info().getPoster_url()==null||getPosterBean.getData().getVideo_info().getPoster_url().equals("")){
                    Bitmap thumbBmp = BitmapFactory.decodeResource(getResources(), R.mipmap.main_yao);
                    msg.thumbData = Util.bmpToByteArray(thumbBmp, true);

//构造一个Req
                    SendMessageToWX.Req req = new SendMessageToWX.Req();
                    req.transaction = buildTransaction("webpage");
                    req.message = msg;
                    req.scene = SendMessageToWX.Req.WXSceneSession;  // 目前只支持会话
//调用api接口，发送数据到微信
                    api.sendReq(req);
                }else {
                    initNetWorkImage(api,PosterActivity.this,Constant.PATH+getPosterBean.getData().getVideo_info().getPoster_url(),"weChat",msg);
                }



                Map<String,String> map=new HashMap<>();
                map.put("token",Constant.TOKEN);
                map.put("target_id",poster_id);
                map.put("uid",uid);
                map.put("type","3");
                pressenter.sendMessage(PosterActivity.this,Constant.add_share,map, Bean.class);

                break;
                default:
        }
    }

    @SuppressLint("StaticFieldLeak")
    public static void initNetWorkImage(final IWXAPI wxapi, final Context context, final String imgUrl, final String flag, final WXMediaMessage msg) {
        new AsyncTask<Void, Void, Bitmap>() {

            @Override
            protected Bitmap doInBackground(Void... voids) {
                Bitmap bitmap = null;
                try {
                    bitmap = Glide.with(context)
                            .asBitmap()
                            .load(imgUrl)
                            .submit(100, 100).get();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                return bitmap;
            }

            @Override
            protected void onPostExecute(Bitmap bitmap) {
                msg.thumbData = WXUtil.bitmap2Bytes(bitmap, 150);
                SendMessageToWX.Req req = new SendMessageToWX.Req();
                req.transaction = buildTransaction("webpage");
                req.message = msg;
                if (flag.equals("weChat")) {
                    req.scene = SendMessageToWX.Req.WXSceneSession;
                } else if (flag.equals("friends")) {
                    req.scene = SendMessageToWX.Req.WXSceneTimeline;
                }
                wxapi.sendReq(req);
            }
        }.execute();
    }

    private static String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }


}
